import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
from config.config import email_config

class EmailUtils:
    """
    邮件工具类，提供发送邮件的方法
    """
    
    @staticmethod
    def send_email(to_list, subject, content, cc_list=None, attachments=None):
        """
        发送邮件
        :param to_list: 收件人列表
        :param subject: 邮件主题
        :param content: 邮件内容
        :param cc_list: 抄送人列表（可选）
        :param attachments: 附件列表（可选，每个附件为字典，包含file_path和file_name）
        :return: 是否发送成功
        """
        # 创建邮件对象
        message = MIMEMultipart()
        message['From'] = Header(email_config.SENDER)
        message['To'] = Header(';'.join(to_list)) if isinstance(to_list, list) else Header(to_list)
        message['Subject'] = Header(subject, 'utf-8')
        
        # 添加抄送人
        if cc_list:
            message['Cc'] = Header(';'.join(cc_list)) if isinstance(cc_list, list) else Header(cc_list)
            to_list = to_list + cc_list if isinstance(to_list, list) and isinstance(cc_list, list) else to_list
        
        # 添加邮件正文
        message.attach(MIMEText(content, 'html', 'utf-8'))
        
        # 添加附件
        if attachments:
            for attachment in attachments:
                file_path = attachment.get('file_path')
                file_name = attachment.get('file_name') or file_path.split('/')[-1].split('\\')[-1]
                
                with open(file_path, 'rb') as f:
                    part = MIMEApplication(f.read())
                    part.add_header('Content-Disposition', 'attachment', filename=Header(file_name, 'utf-8').encode())
                    message.attach(part)
        
        try:
            # 连接SMTP服务器
            if email_config.SMTP_PORT == 465:
                # SSL加密方式
                server = smtplib.SMTP_SSL(email_config.SMTP_SERVER, email_config.SMTP_PORT)
            else:
                # 非SSL加密方式
                server = smtplib.SMTP(email_config.SMTP_SERVER, email_config.SMTP_PORT)
                if email_config.SMTP_PORT == 587:
                    server.starttls()
            
            # 登录邮箱
            server.login(email_config.SMTP_USER, email_config.SMTP_PASSWORD)
            
            # 发送邮件
            if isinstance(to_list, list):
                server.sendmail(email_config.SENDER, to_list, message.as_string())
            else:
                server.sendmail(email_config.SENDER, [to_list], message.as_string())
            
            # 关闭连接
            server.quit()
            return True
        except Exception as e:
            raise Exception(f"邮件发送失败: {str(e)}")
    
    @staticmethod
    def send_text_email(to_list, subject, content, cc_list=None):
        """
        发送纯文本邮件
        :param to_list: 收件人列表
        :param subject: 邮件主题
        :param content: 邮件内容
        :param cc_list: 抄送人列表（可选）
        :return: 是否发送成功
        """
        return EmailUtils.send_email(to_list, subject, f'<pre>{content}</pre>', cc_list)
    
    @staticmethod
    def send_test_report(to_list, subject, report_path, cc_list=None):
        """
        发送测试报告邮件
        :param to_list: 收件人列表
        :param subject: 邮件主题
        :param report_path: 报告文件路径
        :param cc_list: 抄送人列表（可选）
        :return: 是否发送成功
        """
        content = f"<p>测试报告已生成，请查收附件。</p>"
        attachments = [{"file_path": report_path}]
        return EmailUtils.send_email(to_list, subject, content, cc_list, attachments)

# 创建全局实例
email_utils = EmailUtils()